#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QFileDialog>
#include <QTimer>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setStyleSheet("font: 18px Microsoft YaHei");
    this->setWindowTitle("语法高亮");

    codeRadioGroup = new QButtonGroup();
    codeRadioGroup->addButton(ui->radioFile,0);
    codeRadioGroup->addButton(ui->radioKeyboard,1);

    //信号-代码高亮 选择文件
    connect(ui->btnCodeBrowse,&QPushButton::clicked,this,[=]{
        QString fileName = QFileDialog::getOpenFileName(this,"打开文件",QDir::currentPath(),"CODE FIles (*.cpp *.h)");
        if(fileName != nullptr)
        {
            loadFile(ui->codeEditor,fileName);
        }
    });
    connect(ui->chkCode,&QCheckBox::stateChanged,this,[=]{
        if(ui->chkCode->isChecked()){
            codeHighLighter = new CodeHighLighter(ui->codeEditor->document());
        }else{
            delete codeHighLighter;
        }
    });
    connect(ui->radioFile,&QRadioButton::clicked,this,&Widget::codeRadioClicked);
    connect(ui->radioKeyboard,&QRadioButton::clicked,this,&Widget::codeRadioClicked);
    codeTimer = new QTimer;
    connect(codeTimer,&QTimer::timeout,this,&Widget::onCodeTimeout);
    codeCharIndex=0;
    ui->radioFile->click();

}

Widget::~Widget()
{
    delete ui;
}

//选择文件
void Widget::loadFile(QTextEdit *textEdit, QString fileName)
{
    QFile file(fileName);
    file.open(QIODevice::ReadOnly);
    QByteArray array = file.readAll();
    file.close();
    textEdit->setPlainText(QString(array));
}

void Widget::codeRadioClicked()
{
    int checkedId = codeRadioGroup->checkedId();
    if(checkedId == 0){
        ui->btnCodeBrowse->setEnabled(true);
        codeTimer->stop();
        ui->codeEditor->clear();
    }else if(checkedId == 1){
        ui->btnCodeBrowse->setEnabled(false);
        ui->codeEditor->clear();

        QFile* file = new QFile(":/res/widget.cpp");
        file->open(QIODevice::ReadOnly);

        QByteArray array = file->readAll();
        file->close();
        codeString = QString(array);
        codeCharIndex = 0;

        codeTimer->start(20);
    }
}

void Widget::onCodeTimeout()
{
    if(codeCharIndex < codeString.count())
    {
        QString ch = codeString.at(codeCharIndex++);
        if(ch != "\n")
        {
            ui->codeEditor->insertPlainText(ch);
            ui->codeEditor->moveCursor(QTextCursor::End);//将光标移到最后一行
        }
    }
    else{
        codeCharIndex = 0;
        ui->codeEditor->clear();
    }

}
